package com.school.common.util;

import java.util.Random;

public class StringUtils {
	// 取得随机数用
	private static Random randGen = new Random();

	private static char[] numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz" + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();

	/**
	 * 取得一个随机字符串,包含数字和字符
	 * 
	 * 
	 * @param length
	 *            字符串长度
	 * 
	 * @return 随机字符串
	 * 
	 */
	public static final String getRandomString(int length) {
		if (length < 1) {
			return null;
		}
		char[] randBuffer = new char[length];
		for (int i = 0; i < randBuffer.length; i++) {
			randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
		}
		return new String(randBuffer);
	}

	public static final String getRandomString() {
		Random random = new Random();
		return Math.abs(random.nextLong()) + "";
	}

	public static final String getRandomNum(int length) {
		Random random = new Random();
		String result = Math.abs(random.nextLong()) + "";
		return result.substring(0, length - 1);
	}

	/**
	 * 得到字符的长度，一个中文字符算两个长度
	 * 
	 * @param s
	 * @return
	 */
	public static int len(String s) {
		if (s == null)
			return 0;
		int ln = 0, i = 0;
		char c;
		for (i = 0; i < s.length(); i++) {
			c = s.charAt(i);
			if (c >= ' ' && c <= '~') // 所有单字节字符
				ln += 1;
			else
				ln += 2;
		}
		return ln;
	}

	public static String justify(String s, int ln) {
		int sLen = len(s);
		String t = "";
		if (sLen <= ln)
			t = s;
		else
			t = cut(s, ln - 3) + "...";
		return t;
	}

	public static String cut(String s, int xlen) {
		if (s == null) {
			s = "";
		}
		int ln = 0, i = 0;
		String t = "";
		char c;
		for (i = 0; i < s.length(); i++) {
			c = s.charAt(i);
			if (c >= ' ' && c <= '~') //
				ln += 1;
			else
				ln += 2;
			if (ln == xlen) {
				i++;
				t = s.substring(0, i);
				break;
			} else if (ln > xlen) {
				t = s.substring(0, i) + " ";
				break;
			}
		}
		return t;
	}

	public static String byteUnitTrans(long l) {
		String num = l + "";
		String unit = "B";
		float f = 1024;
		double p2 = Math.pow(f, 2);
		double p3 = Math.pow(f, 3);
		if (l > 0) {
			if (l >= f && l < p2) {
				num = (l / f) + "";
				if (num.indexOf(".") != -1) {
					num = num.substring(0, num.indexOf(".") + 2);
				}
				unit = "KB";
			}
			if (l >= p2 && l < p3) {
				num = (l / p2) + "";
				if (num.indexOf(".") != -1) {
					num = num.substring(0, num.indexOf(".") + 2);
				}
				unit = "MB";
			}
			if (l >= p3) {
				num = (l / p3) + "";
				if (num.indexOf(".") != -1) {
					num = num.substring(0, num.indexOf(".") + 2);
				}
				unit = "GB";
			}
		}
		return num + unit;
	}

	public static void main(String[] args) {
		System.out.println(StringUtils.byteUnitTrans(1048576));
	}
}
